-- 该组件提供了lua和unity.gameobject交互的所有接口


-- 模块定义
local M = 
{
	_base_class = require "objects.object",
	_class_name = "objects.UnityGameObject"
}
setmetatable (M, {__index = _G;});
_ENV = M;

-- 引用模块
local Tools = require ("tools.CommonTools");

-- 方法定义
operation_table = Tools.CreateOperationTable (_base_class);

-- 创建空的GameObject
function operation_table.CreateEmptyGO (self)
	if (self._model ~= nil) then
		return;
	end

	self._model = UnityGameObjectLib.NewGameObject ();
end

-- 创建基本形状
function operation_table.CreatePrimitive (self, primativeType)
	if (self._model ~= nil) then
		return;
	end

	self._model = UnityGameObjectLib.CreatePrimitive (primativeType);
end

-- 销毁由CreateEmptyGO、CreatePrimitive创建的GameObject
function operation_table.DestroyGO (self)
	if (self._model == nil) then return end;

	UnityObjectLib.Destroy (self._model);
	self:ModelDestroyed ();
end

-- 加载模型。如果组件已经和模型关联，则在1/30秒后回调load_callback，以模拟异步通知
-- @prefab_id 预设的id
-- @load_callback 模型加载成功后的回调，以unity_game_object对象为参数
function operation_table.LoadModel (self, prefabId, loadCallback)
	if (self._model ~= nil and loadCallback ~= nil) then
		require ("tools.Timer").AddTimer (0.03, 1, nil, 
			function (timerId, timerTimes, param) 
				loadCallback (self);
			end
		);
		return;
	end

	local callback = function (gameModel, functionRef) 
		FFIToolsLib.LuaLUnref (functionRef);

		self._model = gameModel;
		-- 添加其它需要的属性

		if (loadCallback ~= nil) then
			loadCallback (self);
		end
	end;
	local callbackRef = FFIToolsLib.LuaLRef (callback);
	UnityGameObjectLib.GetGameObject (prefabId, callbackRef);
end

-- 释放模型
function operation_table.ReleaseModel (self)
	if (self._model == nil) then return end;

	UnityGameObjectLib.ReleaseGameObject (self._model);
	self:ModelDestroyed ();
end

-- 模型销毁/释放后的回调 
function operation_table.ModelDestroyed ()
	self._model = nil;
	self._transform = nil;
end

-- 获取transform对象
function operation_table.GetTransform (self)
	if (self._transform ~= nil) then
		return self._transform;
	elseif (self._model ~= nil) then
		self._transform = self._model:GetTransform ();
		return self._transform;
	else
		return nil;
	end
end

-- 构造方法
function NewUnityGameObject ()
	local instance = _base_class.NewObject ();
	Tools.PrepareInstance (M, instance);
	
	-- 在这里定义成员变量
	instance._model = nil;
	instance._transform = nil;

	
	return instance;
end;

return M;